/**
 * ImageImportTransferHandler.java
 * 
 * @date: 2012-02-09
 * @author: Xiaoyu Guo (MUN# 200982155)
 * This file is part of the course project for COMP 6752, 
 * Application of Computer Graphics. All the file is written
 * by myself.
 */
package mun.cs6752.project.ui.transfer;

import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.TransferHandler;

import mun.cs6752.project.FilterMainFrame;

/**
 * @author Xiaoyu Guo
 *
 */
public class ImageImportTransferHandler extends TransferHandler {
    private static final long serialVersionUID = 6247512459922100415L;

    public boolean canImport(TransferSupport support){
        if(!support.isDrop()){
            return false;
        }
        
        if(!support.isDataFlavorSupported(DataFlavor.imageFlavor) && !support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){
            return false;
        }
        
        if(!(support.getComponent() instanceof FilterMainFrame)){
            return false;
        }
        return true;
    }
    
    public boolean importData(TransferSupport support){
        Transferable data = support.getTransferable();

        if(!canImport(support)) 
        {  
            return false;  
        }
        
        FilterMainFrame canvas = (FilterMainFrame) support.getComponent();
        try {
            if(support.isDataFlavorSupported(DataFlavor.imageFlavor)){
                Image img = (Image) data.getTransferData(DataFlavor.imageFlavor);
            } else if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){
                List<File> files = (List<File>) data.getTransferData(DataFlavor.javaFileListFlavor);
                if(files != null && files.size() > 0){
                    canvas.openImage(files.get(0));
                }
            }
            return true;
        } catch (UnsupportedFlavorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
}
